package com.xmy.cultivate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ArrivalRate;
import com.xmy.cultivate.entity.response.RepairLessonRs;
import com.xmy.cultivate.entity.views.LeadDataRs;
import com.xmy.cultivate.entity.views.StudentClassLogRep;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.feign.erp_admin.IAdminFeignClient;
import com.xmy.cultivate.feign.math_outside.IMathematicsFeignClient;
import com.xmy.cultivate.feign.physics_outside.IPhysicsFeignClient;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.AssignMoney;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 记止课 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-08-10
 */
@Service
public class RecordCourseServiceImpl extends ServiceImpl<RecordCourseMapper, RecordCourse> implements IRecordCourseService {

    @Autowired
    IdWorker idWorker;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    ISubjectsService iSubjectsService;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    IRecordCostService iRecordCostService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IRecordErrorService iRecordErrorService;

    @Autowired
    IStudentGradeTemporaryService iStudentGradeTemporaryService;

    @Autowired
    ICourseService iCourseService;

    @Autowired
    RenewClassMapper renewClassMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    RepairCourseMapper repairCourseMapper;

    final String mixDateFinal = "1970-01-01";

    @Autowired
    IRecordCourseCheckService iRecordCourseCheckService;

    @Autowired
    IRecordCourseLackService iRecordCourseLackService;

    @Autowired
    RecordCourseLackMapper recordCourseLackMapper;

    @Autowired
    CoursePricingMapper coursePricingMapper;

    @Autowired
    IAdminFeignClient iAdminFeignClient;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Autowired
    TrackMarketMapper trackMarketMapper;

    @Autowired
    ITrackMarketService iTrackMarketService;

    @Autowired
    ISystemErrorLogService iSystemErrorLogService;

    @Autowired
    IAuthAdminContentService iAuthAdminContentService;

    @Autowired
    IMathematicsFeignClient iMathematicsFeignClient;

    @Autowired
    IPhysicsFeignClient iPhysicsFeignClient;

    @Override
    public List<ArrivalRate> arrivalRate(String schoolId, String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate, Integer type, String timeStart, String timeEnd, List<Long> baseSchoolIdList, Integer lessonType, String yearClassId, String trackId, String isTeamDetails, String classify, String trackType, String teamId, String name, String teacherId, String startLessonNum, String endLessonNum, String isCall, String isRebrush, String isYearClass, Long adminId, AuthAdminContent authAdminContent) {
        String schoolStr = "";
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isNotBlank(schoolId)) {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolStr = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);

        } else {
            schoolStr = authAdminContent.getSchoolIds();
        }

        if (StringUtils.isNotBlank(SubjectsId)) {

            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), SubjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            SubjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), SubjectsId);

        } else {
            SubjectsId = authAdminContent.getSubjectsIds();
        }

        if (StringUtils.isNotBlank(yearClassId)) {

            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);

        } else {
            yearClassId = authAdminContent.getYearClassIds();
        }

        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);

        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;

        List<ArrivalRate> arrivalRateList = null;
        Integer rateType = 1;
        if (StringUtils.isNotBlank(startLessonNum) && StringUtils.isNotBlank(endLessonNum)) {
            //按课次查看
//            startDateLast = "";
//            endDateLast = localDateNow.minusDays(1).toString();
            StartDate = localDateNow.toString();
            EndDate = localDateNow.toString();
        } else {
            if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = EndDate;
//                StartDate = mixDate;
//                EndDate = mixDate;
            } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = localDateNow.minusDays(1).toString();
//                StartDate = localDateNow.toString();
            }
        }

        Integer giveCount = recordCourseMapper.getSignGiveCount(YearPart, QuarterNum, localDateNow.toString());
        String readingStatus = "1";
        if (giveCount > 0) {
            readingStatus = "1,5";
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(YearPart, QuarterNum);
        StringBuilder courseSchedulingDetailName = new StringBuilder();
        courseSchedulingDetailName.append("course_scheduling_detail");
        if (quarter.getId() != quarterNow.getId()) {
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(YearPart);
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(QuarterNum);
        }

        if (lessonType.equals(1)) {
            //精品课
            if (type == 5) {
                arrivalRateList = recordCourseMapper.arrivalRateTeam(schoolStr, YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearClassId, isTeamDetails, classify, trackType, teamId, name, startLessonNum, endLessonNum, readingStatus, String.valueOf(courseSchedulingDetailName), isYearClass, authAdminContent, leadDataRs);
            } else {
                arrivalRateList = recordCourseMapper.arrivalRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, rateType, lessonType, null, yearClassId, trackId, name, startLessonNum, endLessonNum, teacherId, readingStatus, String.valueOf(courseSchedulingDetailName), isYearClass, authAdminContent, leadDataRs);
            }
        } else {
            //boolean isHistory = true;//是否历史数据（当天的除外是历史数据）
            //if (YearPart.equals(quarterNow.getYearPart()) && QuarterNum.equals(quarterNow.getNum()) && !localDateNow.isAfter(startDate)) {
            //    isHistory = false;
            //}

            if (isRebrush.equals("1")) {
                Long storSubjectsId = null;
                if (StringUtils.isNotBlank(SubjectsId)) {
                    storSubjectsId = Long.parseLong(SubjectsId);
                }
                //调用存储过程
                recordCourseMapper.storeAgainBrushData(YearPart, QuarterNum, storSubjectsId, yearClassId, null);
            }

            LocalDate planEndDate = LocalDate.now();
            // 判断结束日期是否大于当前日期，如果大于当前日期，那么planEndDate等于结束日期
            if (endDate.isAfter(planEndDate)) {
                planEndDate = endDate;
            }
            Integer tastMaxLessonNum = this.getMaxTaskLesson(YearPart, QuarterNum, SubjectsId, 1676874588501311488L, 1);

            //智能课，刷题班
            if (type == 5) {
                arrivalRateList = recordCourseMapper.reachRateTeam(schoolStr, YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearClassId, isTeamDetails, classify, trackType, teamId, name, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            } else {
                arrivalRateList = recordCourseMapper.reachRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, rateType, null, yearClassId, name, teacherId, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), dateTimeNow.toString(), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            }
        }

        if (type == 6 && StringUtils.isBlank(schoolId)) {
            List<ArrivalRate> collectList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", YearPart.toString());
            queryWrapper.eq("quarter_num", QuarterNum.toString());
            queryWrapper.eq("pid", 0);
            List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

            for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                ArrivalRate arrivalRate = new ArrivalRate();
                arrivalRate.setSchoolId(schoolQuarter.getSchoolId());
                arrivalRate.setSchoolName(schoolQuarter.getSchoolName());
                arrivalRate.setSchoolPid(schoolQuarter.getPid());
                arrivalRate.setStudentAllCount(0);
                arrivalRate.setTardinessRateCount(0);
                arrivalRate.setArrivedCount(0);
                arrivalRate.setNoArrivedCount(0);
                arrivalRate.setTruancyCount(0);

                collectList.add(arrivalRate);
            }

            for (ArrivalRate arrivalRate : collectList) {
                List<ArrivalRate> childRates = new ArrayList<>();
                for (ArrivalRate arrivalRateChild : arrivalRateList) {
                    if (arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                        childRates.add(arrivalRateChild);
                        if (arrivalRateChild.getStudentAllCount() != null) {
                            arrivalRate.setStudentAllCount(arrivalRate.getStudentAllCount() + arrivalRateChild.getStudentAllCount());
                        }
                        if (arrivalRateChild.getTardinessRateCount() != null) {
                            arrivalRate.setTardinessRateCount(arrivalRate.getTardinessRateCount() + arrivalRateChild.getTardinessRateCount());
                        }
                        if (arrivalRateChild.getArrivedCount() != null) {
                            arrivalRate.setArrivedCount(arrivalRate.getArrivedCount() + arrivalRateChild.getArrivedCount());
                        }
                        if (arrivalRateChild.getNoArrivedCount() != null) {
                            arrivalRate.setNoArrivedCount(arrivalRate.getNoArrivedCount() + arrivalRateChild.getNoArrivedCount());
                        }
                        if (arrivalRateChild.getTruancyCount() != null) {
                            arrivalRate.setTruancyCount(arrivalRate.getTruancyCount() + arrivalRateChild.getTruancyCount());
                        }
                    }
                }
                arrivalRate.setChildRateList(childRates);
            }

            arrivalRateList = collectList;
        }

        return arrivalRateList;
    }

    /**
     * 到课率、旷课率详情
     */
    @Override
    public IPage<RecordCourse> arrivalRateDetail(IPage<?> page, String schoolId, String subjectsId, String yearPart, String quarterNum, String StartDate, String EndDate, String gradeId, String teacherId, String type, String status, String timeStart, String timeEnd, Integer lessonType, String detailType, String yearClassIdStr, String classify, String trackType, String teamId, String startLessonNum, String endLessonNum, String isCall, String isRebrush, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();
        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);

        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;

        boolean isHistory = true;//是否历史数据（当天的除外是历史数据）
        if (yearPart.equals(quarterNow.getYearPart().toString()) && quarterNum.equals(quarterNow.getNum().toString()) && StartDate.equals(localDateNow.toString()) && EndDate.equals(localDateNow.toString())) {
            isHistory = false;
        }
        if (StringUtils.isBlank(yearClassIdStr)) {
            yearClassIdStr = "0,1,2,3,4,5,6,7,8,9";
        }
        IPage<RecordCourse> recordCourseList = null;
        Integer rateType = 1;

        if (StringUtils.isNotBlank(startLessonNum) && StringUtils.isNotBlank(endLessonNum)) {
            //按课次查看
//            startDateLast = "";
//            endDateLast = localDateNow.minusDays(1).toString();
            StartDate = localDateNow.toString();
            EndDate = localDateNow.toString();
        } else {
            if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = EndDate;
//                StartDate = mixDate;
//                EndDate = mixDate;
            } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = localDateNow.minusDays(1).toString();
//                StartDate = localDateNow.toString();
            }
        }
        /**
         * 是否赠送时间内
         */
        Integer giveCount = recordCourseMapper.getSignGiveCount(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), localDateNow.toString());
        String readingStatus = "1";
        if (giveCount > 0) {
            readingStatus = "1,5";
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
        StringBuilder courseSchedulingDetailName = new StringBuilder();
        courseSchedulingDetailName.append("course_scheduling_detail");
        if (quarter.getId() != quarterNow.getId()) {
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(yearPart);
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(quarterNum);
        }

        if (lessonType.equals(1)) {
            //精品课
            if (type.equals("5")) {
                recordCourseList = recordCourseMapper.arrivalRateTeamDetail(page, schoolId, yearPart, quarterNum, subjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearClassIdStr, classify, trackType, teamId, teacherId, status, "", gradeId, startLessonNum, endLessonNum, readingStatus, String.valueOf(courseSchedulingDetailName), authAdminContent, leadDataRs);
            } else {
                recordCourseList = recordCourseMapper.arrivalRateDetail(page, schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, type, status, timeStart, timeEnd, lessonType, rateType, yearClassIdStr, "", startLessonNum, endLessonNum, readingStatus, String.valueOf(courseSchedulingDetailName), authAdminContent, leadDataRs);
            }
        } else {

            if (isRebrush.equals("1")) {
                Long storSubjectsId = null;
                if (StringUtils.isNotBlank(subjectsId)) {
                    storSubjectsId = Long.parseLong(subjectsId);
                }
                recordCourseMapper.storeAgainBrushData(Integer.valueOf(yearPart), Integer.valueOf(quarterNum), storSubjectsId, yearClassIdStr, null);
            }

            LocalDate planEndDate = LocalDate.now();
            // 判断结束日期是否大于当前日期，如果大于当前日期，那么planEndDate等于结束日期
            if (endDate.isAfter(planEndDate)) {
                planEndDate = endDate;
            }
            Integer tastMaxLessonNum = this.getMaxTaskLesson(Integer.parseInt(yearPart), Integer.getInteger(quarterNum), subjectsId, 1676874588501311488L, 1);

            // 刷题班和智能课
            if (type.equals("5")) {
                recordCourseList = recordCourseMapper.reachRateTeamDetail(page, schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, type, status, timeStart, timeEnd, lessonType, rateType, isHistory, yearClassIdStr, detailType, classify, trackType, teamId, isCall, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            } else {
                recordCourseList = recordCourseMapper.reachRateDetail(page, schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, type, status, timeStart, timeEnd, lessonType, rateType, isHistory, yearClassIdStr, detailType, isCall, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            }
        }
        return recordCourseList;
    }

    /**
     * 迟到详情
     */
    @Override
    public IPage<RecordCourse> tardinessRateDetail(IPage<?> page, String schoolId, String subjectsId, String yearPart, String quarterNum, String StartDate, String EndDate, String gradeId, String teacherId, String type, String status, String timeStart, String timeEnd, Integer lessonType, String mode, String punctuality, String punctualityType, String yearClassIdStr, String classify, String trackType, String teamId, String startLessonNum, String endLessonNum, String isCall, String detailType, String isRebrush, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();
        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);
        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;
        if (StringUtils.isBlank(yearClassIdStr)) {
            yearClassIdStr = "0,1,2,3,4,5,6,7,8,9";
        }
        boolean isHistory = true;//是否历史数据（当天的除外是历史数据）
        if (yearPart.equals(quarterNow.getYearPart().toString()) && quarterNum.equals(quarterNow.getNum().toString()) && StartDate.equals(localDateNow.toString()) && EndDate.equals(localDateNow.toString())) {
            isHistory = false;
        }
        IPage<RecordCourse> recordCourseList = null;

        Integer rateType = 2;//1到课率，2迟到率
        if (StringUtils.isNotBlank(startLessonNum) && StringUtils.isNotBlank(endLessonNum)) {
            //按课次查看
//            startDateLast = "";
//            endDateLast = localDateNow.minusDays(1).toString();
            StartDate = localDateNow.toString();
            EndDate = localDateNow.toString();
        } else {
            if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = EndDate;
//                StartDate = mixDate;
//                EndDate = mixDate;
            } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = localDateNow.minusDays(1).toString();
//                StartDate = localDateNow.toString();
            }
        }

        /**
         * 是否赠送时间内
         */
        Integer giveCount = recordCourseMapper.getSignGiveCount(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), localDateNow.toString());
        String readingStatus = "1";
        if (giveCount > 0) {
            readingStatus = "1,5";
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
        StringBuilder courseSchedulingDetailName = new StringBuilder();
        courseSchedulingDetailName.append("course_scheduling_detail");
        if (quarter.getId() != quarterNow.getId()) {
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(yearPart);
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(quarterNum);
        }

        if (lessonType.equals(1)) {
            if (punctualityType.equals("0")) {
                //status = "2";
            } else {
                status = "1";
            }
            if (type.equals("5")) {
                recordCourseList = recordCourseMapper.arrivalRateTeamDetail(page, schoolId, yearPart, quarterNum, subjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearClassIdStr, classify, trackType, teamId, teacherId, status, punctualityType, gradeId, startLessonNum, endLessonNum, readingStatus, String.valueOf(courseSchedulingDetailName), authAdminContent, leadDataRs);
            } else {
                recordCourseList = recordCourseMapper.arrivalRateDetail(page, schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, type, status, timeStart, timeEnd, lessonType, rateType, yearClassIdStr, punctualityType, startLessonNum, endLessonNum, readingStatus, String.valueOf(courseSchedulingDetailName), authAdminContent, leadDataRs);
            }
        } else {

            if (isRebrush.equals("1")) {
                recordCourseMapper.storeAgainBrushData(Integer.valueOf(yearPart), Integer.valueOf(quarterNum), Long.parseLong(subjectsId), yearClassIdStr, null);
            }

            LocalDate planEndDate = LocalDate.now();
            // 判断结束日期是否大于当前日期，如果大于当前日期，那么planEndDate等于结束日期
            if (endDate.isAfter(planEndDate)) {
                planEndDate = endDate;
            }
            Integer tastMaxLessonNum = this.getMaxTaskLesson(Integer.parseInt(yearPart), Integer.getInteger(quarterNum), subjectsId, 1676874588501311488L, 1);

            if (type.equals("5")) {
                recordCourseList = recordCourseMapper.reachRateTeamDetail(page, schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, type, status, timeStart, timeEnd, lessonType, rateType, isHistory, yearClassIdStr, detailType, classify, trackType, teamId, isCall, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            } else {
                recordCourseList = recordCourseMapper.reachRateDetail(page, schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, type, status, timeStart, timeEnd, lessonType, rateType, isHistory, yearClassIdStr, detailType, isCall, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            }
        }
        return recordCourseList;
    }

    /**
     * 课时提成
     *
     * @param reMap
     * @return
     */
    @Override
    public List<AssignMoney> classHouseMoney(Map reMap) {
        String quarterNum = (String) reMap.get("quarterNum");
        String yearPart = (String) reMap.get("yearPart");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String subjectId = (String) reMap.get("subjectId");
        String schoolId = (String) reMap.get("schoolId");
        String type = (String) reMap.get("type");
        String adminId = (String) reMap.get("adminId");
        String isSuper = (String) reMap.get("isSuper");

        List<AssignMoney> recordCourseList = null;

        /**
         * 个人
         */
        if (type.equals("1")) {
            recordCourseList = recordCourseMapper.classHouseMoneyType1AndType3(schoolId, subjectId, yearPart, quarterNum, startDate, endDate, type, isSuper);
        }
        /**
         * 校区老师
         */
        if (type.equals("2")) {
            if (isSuper.equals("1")) {
                recordCourseList = recordCourseMapper.classHouseMoneyAdminType2(schoolId, subjectId, yearPart, quarterNum, startDate, endDate, type, isSuper);
            } else {
                Staff staff = staffMapper.selectByAdminId(Long.valueOf(adminId));
                schoolId = String.valueOf(staff.getSchoolId());
                recordCourseList = recordCourseMapper.classHouseMoneyType2AndType4(schoolId, subjectId, yearPart, quarterNum, startDate, endDate, type, isSuper);
            }
        }
        /**
         * 校长
         */
        if (type.equals("3")) {
            recordCourseList = recordCourseMapper.classHouseMoneyType1AndType3(schoolId, subjectId, yearPart, quarterNum, startDate, endDate, type, isSuper);
        }
        /**
         * 校区
         */
        if (type.equals("4")) {
            recordCourseList = recordCourseMapper.classHouseMoneyType2AndType4(schoolId, subjectId, yearPart, quarterNum, startDate, endDate, type, isSuper);
        }
        return recordCourseList;
    }

    @Override
    public Integer headcount(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String quarterNum = (String) reMap.get("quarterNum");
        String yearPart = (String) reMap.get("yearPart");
        String type = (String) reMap.get("type");
        String isSuper = (String) reMap.get("isSuper");
        String teacherId = (String) reMap.get("teacherId");

        Integer headcount = recordCourseMapper.headcount(schoolId, yearPart, quarterNum, type, isSuper, teacherId);

        return headcount;
    }

    @Override
    public HashMap<String, Integer> getRepairCourse(Map reMap) {
        String schoolId = (String) reMap.get("schoolId");
        String teacherId = (String) reMap.get("teacherId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String yearPart = (String) reMap.get("yearPart");

        //补课、调课
        Integer repairCount = recordCourseMapper.getRepairCourse(schoolId, teacherId, startDate, endDate);
        Integer repairMayMoney = recordCourseMapper.getRepairMayMoney(schoolId, teacherId, startDate, endDate);
        //请假未补
        Integer getLeaveLack = recordCourseMapper.getLeaveLack(schoolId, teacherId, startDate, endDate);
        //排课未上
        Integer getClassesNotScheduled = recordCourseMapper.getClassesNotScheduled(startDate, endDate, schoolId, yearPart, teacherId);
        //缺课未补
        Integer getClassesVacancy = recordCourseMapper.getClassesVacancy(startDate, endDate, schoolId, yearPart, teacherId);
        Integer unfinishedClass = 0;
        if (getLeaveLack != null) {
            unfinishedClass += getLeaveLack;
        }
        if (getClassesNotScheduled != null) {
            unfinishedClass += getClassesNotScheduled;
        }
        if (getClassesVacancy != null) {
            unfinishedClass += getClassesVacancy;
        }

        HashMap hashMap = new HashMap<>();
        //补课、调课人数
        hashMap.put("repairCount", repairCount);
        //补课、调课课时提成
        hashMap.put("repairMayMoney", repairMayMoney);
        //未消
        hashMap.put("unfinishedClass", unfinishedClass);

        return hashMap;
    }

    @Override
    public List<CancellationRate> selectCancellationRate(String schoolId, Integer yearPart, Integer quarterNum, String subjectsId, Integer type, LocalDateTime startDate, LocalDateTime endDate, String lessonType, String yearClassId, String classTypeIdStr, String startLessonNum, String endLessonNum, String teacherId, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        LocalDateTime endDateTimeBefore = endDate;//endDate.minusDays(1)
        // 设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedEndDateTimeBefore = endDateTimeBefore.format(formatter);

        List<CancellationRate> cancellationRates = recordCourseMapper.cancellationRate(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, lessonType, yearClassId, classTypeIdStr, formattedEndDateTimeBefore, startLessonNum, endLessonNum, teacherId, authAdminContent, leadDataRs);
        return cancellationRates;
    }

    @Override
    public IPage<CancellationRate> cancellationRateDetail(IPage<?> iPage, String schoolId, Long teacherId, Integer yearPart, Integer quarterNum, String subjectsId, Integer type, LocalDateTime startDate, LocalDateTime endDate, String lessonType, String gradeId, Integer detailType, String yearClassId, String classTypeIdStr, String startLessonNum, String endLessonNum, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        // 获取上一天的时间
        LocalDateTime endDateTimeBefore = endDate;//endDate.minusDays(1);
        // 设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedEndDateTimeBefore = endDateTimeBefore.format(formatter);

        return recordCourseMapper.cancellationRateDetail(iPage, schoolId, teacherId, yearPart, quarterNum, subjectsId, type, startDate, endDate, lessonType, gradeId, detailType, yearClassId, classTypeIdStr, formattedEndDateTimeBefore, startLessonNum, endLessonNum, authAdminContent, leadDataRs);
    }

    @Override
    public List<CancellationRate> cancellationRateTeamList(String schoolId, Integer yearPart, Integer quarterNum, String subjectsId, LocalDateTime startDate, LocalDateTime endDate, String yearClassId, String classTypeIdStr, String teamId, String classify, String trackType, String startLessonNum, String endLessonNum, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        LocalDateTime endDateTimeBefore = endDate;
        // 设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedEndDateTimeBefore = endDateTimeBefore.format(formatter);

        StringBuilder ids = new StringBuilder();
        TrackMarket market = trackMarketMapper.selectById(teamId);
        if (Objects.nonNull(teamId) && Objects.nonNull(market)) {
            ids.append(teamId);
            if (market.getPid().equals(0) || market.getPid() == 0L) {
                String idByPid = trackMarketMapper.getIdByPid(market.getId(), String.valueOf(yearPart), String.valueOf(quarterNum), Integer.valueOf(classify));
                if (StringUtils.isNotBlank(idByPid)) {
                    ids.append(",");
                    ids.append(idByPid);
                }
            }
        }
        List<CancellationRate> cancellationRates = recordCourseMapper.cancellationRateTeamList(schoolId, yearPart, quarterNum, subjectsId, startDate, endDate, yearClassId, classTypeIdStr, formattedEndDateTimeBefore, String.valueOf(ids), classify, trackType, startLessonNum, endLessonNum, authAdminContent, leadDataRs);

        return cancellationRates;
    }

    @Override
    public IPage<CancellationRate> cancellationRateTeamDetail(IPage<?> iPage, String schoolId, Long teacherId, Integer yearPart, Integer quarterNum, String subjectsId, LocalDateTime startDate, LocalDateTime endDate, String gradeId, Integer detailType, String yearClassId, String classTypeIdStr, String teamId, String classify, String trackType, String startLessonNum, String endLessonNum, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        LocalDateTime endDateTimeBefore = endDate;
        // 设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String formattedEndDateTimeBefore = endDateTimeBefore.format(formatter);

        return recordCourseMapper.cancellationRateTeamDetail(iPage, schoolId, teacherId, yearPart, quarterNum, subjectsId, startDate, endDate, gradeId, detailType, yearClassId, classTypeIdStr, formattedEndDateTimeBefore, teamId, classify, trackType, startLessonNum, endLessonNum, authAdminContent, leadDataRs);
    }

    public List<RecordCourse> selectExamination(QueryWrapper queryWrapper, String nowData) {
        queryWrapper.ne("course_type", 3);
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(queryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            recordCourse.setShouldCount(this.getGradeStudyCount(recordCourse.getGradeId(), nowData));
            recordCourse.setSolidCount(this.getSolidCount(recordCourse.getGradeId(), 1, nowData));
            recordCourse.setLeaveCount(this.getSolidCount(recordCourse.getGradeId(), 2, nowData));
        }
        return recordCourseList;
    }

    public Integer getGradeStudyCount(Long gradeId, String nowData) {
        QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade_id", gradeId);
        queryWrapper.ne("course_type", 2);
        queryWrapper.ne("course_type", 3);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("school_date", nowData);
        Long count = recordCourseMapper.selectCount(queryWrapper);
        return Integer.valueOf(count.toString());
    }

    public Integer getSolidCount(Long gradeId, Integer status, String nowData) {
        QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade_id", gradeId);
        queryWrapper.eq("status", status);
        queryWrapper.notIn("course_type", 2, 3);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("school_date", nowData);
        Long solidCount = recordCourseMapper.selectCount(queryWrapper);
        return Integer.valueOf(solidCount.toString());
    }

    /**
     * 迟到率
     */
    @Override
    public List<ArrivalRate> tardinessRate(String[] schoolIdList, String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate, Integer type, String timeStart, String timeEnd, List<Long> baseSchoolIdList, Integer lessonType, String schoolId, String yearCalssIdStr, String trackId, String isTeamDetails, String classify, String trackType, String teamId, String name, String startLessonNum, String endLessonNum, String teacherId, String isRebrush, String isYearClass, AuthAdminContent authAdminContent) {
        String schoolStr = "";
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isNotBlank(schoolId)) {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            String schoolIdTemp = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
            schoolStr = schoolIdTemp;

        } else {
            schoolStr = authAdminContent.getSchoolIds();
        }

        if (StringUtils.isNotBlank(SubjectsId)) {

            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), SubjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            String subjectsIdTemp = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), SubjectsId);
            SubjectsId = subjectsIdTemp;

        } else {
            SubjectsId = authAdminContent.getSubjectsIds();
        }

        if (StringUtils.isNotBlank(yearCalssIdStr)) {

            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearCalssIdStr);
            leadDataRs.setYearClassIds(leadYearClassId);

            String yearClassIdTemp = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearCalssIdStr);
            yearCalssIdStr = yearClassIdTemp;

        } else {
            yearCalssIdStr = authAdminContent.getYearClassIds();
        }

        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();
        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);

        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;

        List<ArrivalRate> arrivalRateList = null;
        Integer rateType = 2;//1到课率，2迟到率
        if (StringUtils.isNotBlank(startLessonNum) && StringUtils.isNotBlank(endLessonNum)) {
            //按课次查看
//            startDateLast = "";
//            endDateLast = localDateNow.minusDays(1).toString();
            StartDate = localDateNow.toString();
            EndDate = localDateNow.toString();
        } else {
            if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = EndDate;
//                StartDate = mixDate;
//                EndDate = mixDate;
            } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = localDateNow.minusDays(1).toString();
//                StartDate = localDateNow.toString();
            }
        }

        /**
         * 是否赠送时间内
         */
        Integer giveCount = recordCourseMapper.getSignGiveCount(YearPart, QuarterNum, localDateNow.toString());
        String readingStatus = "1";
        if (giveCount > 0) {
            readingStatus = "1,5";
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(YearPart, QuarterNum);
        StringBuilder courseSchedulingDetailName = new StringBuilder();
        courseSchedulingDetailName.append("course_scheduling_detail");
        if (quarter.getId() != quarterNow.getId()) {
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(YearPart);
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(QuarterNum);
        }

        if (lessonType.equals(1)) {
            //精品课
            if (type != 5) {
                arrivalRateList = recordCourseMapper.arrivalRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, rateType, schoolId, yearCalssIdStr, trackId, name, startLessonNum, endLessonNum, teacherId, readingStatus, String.valueOf(courseSchedulingDetailName), isYearClass, authAdminContent, leadDataRs);
            } else if (type == 5) {
                arrivalRateList = recordCourseMapper.arrivalRateTeam(schoolStr, YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearCalssIdStr, isTeamDetails, classify, trackType, teamId, name, startLessonNum, endLessonNum, readingStatus, String.valueOf(courseSchedulingDetailName), isYearClass, authAdminContent, leadDataRs);
            }
            //精品课
        } else {
            boolean isHistory = true;//是否历史数据（当天的除外是历史数据）
            if (YearPart.equals(quarterNow.getYearPart()) && QuarterNum.equals(quarterNow.getNum()) && !localDateNow.isAfter(startDate)) {
                isHistory = false;
            }
            if (isRebrush.equals("1")) {
                recordCourseMapper.storeAgainBrushData(Integer.valueOf(YearPart), Integer.valueOf(QuarterNum), Long.parseLong(SubjectsId), yearCalssIdStr, null);
            }

            LocalDate planEndDate = LocalDate.now();
            // 判断结束日期是否大于当前日期，如果大于当前日期，那么planEndDate等于结束日期
            if (endDate.isAfter(planEndDate)) {
                planEndDate = endDate;
            }
            Integer tastMaxLessonNum = 20;
            try {
                if (SubjectsId.equals("2")) {
                    tastMaxLessonNum = iMathematicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(), QuarterNum.toString(), SubjectsId, 1676874588501311488L, 1);
                } else if (SubjectsId.equals("3")) {
                    tastMaxLessonNum = iPhysicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(), QuarterNum.toString(), SubjectsId, 1676874588501311488L, 1);
                }
            } catch (Exception e) {
            }


            //智能课，刷题班
            if (type == 5) {
                arrivalRateList = recordCourseMapper.reachRateTeam(schoolStr, YearPart.toString(), QuarterNum.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, yearCalssIdStr, isTeamDetails, classify, trackType, teamId, name, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            } else {
                arrivalRateList = recordCourseMapper.reachRate(schoolStr, YearPart.toString(), QuarterNum.toString(), type.toString(), SubjectsId, startDateLast, endDateLast, StartDate, EndDate, timeStart, timeEnd, lessonType, rateType, null, yearCalssIdStr, name, teacherId, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), dateTimeNow.toString(), String.valueOf(planEndDate), authAdminContent, leadDataRs, tastMaxLessonNum);
            }
        }

        if (type == 6 && StringUtils.isBlank(schoolId)) {
            List<ArrivalRate> collectList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", YearPart.toString());
            queryWrapper.eq("quarter_num", QuarterNum.toString());
            queryWrapper.eq("pid", 0);
            List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

            for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                ArrivalRate arrivalRate = new ArrivalRate();
                arrivalRate.setSchoolId(schoolQuarter.getSchoolId());
                arrivalRate.setSchoolName(schoolQuarter.getSchoolName());
                arrivalRate.setSchoolPid(schoolQuarter.getPid());
                arrivalRate.setStudentAllCount(0);
                arrivalRate.setTardinessRateCount(0);
                arrivalRate.setArrivedCount(0);
                arrivalRate.setNoArrivedCount(0);
                arrivalRate.setLeaveCount(0);

                collectList.add(arrivalRate);
            }

            for (ArrivalRate arrivalRate : collectList) {
                List<ArrivalRate> childRates = new ArrayList<>();
                for (ArrivalRate arrivalRateChild : arrivalRateList) {
                    if (arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || arrivalRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                        childRates.add(arrivalRateChild);
                        if (arrivalRateChild.getStudentAllCount() != null) {
                            arrivalRate.setStudentAllCount(arrivalRateChild.getStudentAllCount() + arrivalRate.getStudentAllCount());
                        }
                        if (arrivalRateChild.getTardinessRateCount() != null) {
                            arrivalRate.setTardinessRateCount(arrivalRateChild.getTardinessRateCount() + arrivalRate.getTardinessRateCount());
                        }
                        if (arrivalRateChild.getArrivedCount() != null) {
                            arrivalRate.setArrivedCount(arrivalRateChild.getArrivedCount() + arrivalRate.getArrivedCount());
                        }
                        if (arrivalRateChild.getNoArrivedCount() != null) {
                            arrivalRate.setNoArrivedCount(arrivalRateChild.getNoArrivedCount() + arrivalRate.getNoArrivedCount());
                        }
                        if (arrivalRateChild.getLeaveCount() != null) {
                            arrivalRate.setLeaveCount(arrivalRateChild.getLeaveCount() + arrivalRate.getLeaveCount());
                        }
                    }
                }
                arrivalRate.setChildRateList(childRates);
            }

            return collectList;
        }


        return arrivalRateList;
    }

    @Override
    public List<RepairLessonRs> getRepairLesson(String schoolIdStr, String schoolId, String yearPart, String quarterNum, String type, String subjectsId, String startDate, String endDate, Integer lessonType, String yearClassId) {
        Quarter quarter = iQuarterService.getNowQuarter();
        Integer isHistory = 1;
        if (quarter.getNum().equals(Integer.valueOf(quarterNum)) && quarter.getYearPart().equals(Integer.valueOf(yearPart))) {
            isHistory = 0;
        }
        return recordCourseMapper.getRepairLesson(schoolIdStr, schoolId, yearPart, quarterNum, type, subjectsId, startDate, endDate, lessonType, isHistory, yearClassId);
    }

    @Override
    public List<RepairLessonRs> getRepairLessonDetail(String schoolIdStr, String yearPart, String quarterNum, String type, String subjectsId, String startDate, String endDate, Integer lessonType, Long teacherId, String gradeId, String studentName, String yearClassId) {
        return recordCourseMapper.getRepairLessonDetail(schoolIdStr, yearPart, quarterNum, type, subjectsId, startDate, endDate, lessonType, teacherId, gradeId, studentName, yearClassId);
    }

    @Override
    public List<RepairLessonRs> getRepairLessonTeamList(String yearPart, String quarterNum, String type, String subjectsId, String startDate, String endDate, Integer lessonType, String yearClassId, String classify, String trackType, String teamId) {
        return recordCourseMapper.getRepairLessonTeamList(yearPart, quarterNum, type, subjectsId, startDate, endDate, lessonType, yearClassId, classify, trackType, teamId);
    }

    @Override
    public List<RepairLessonRs> getRepairLessonTeamDetail(String yearPart, String quarterNum, String type, String subjectsId, String startDate, String endDate, Integer lessonType, Long teacherId, String gradeId, String studentName, String yearClassId, String classify, String trackType, String teamId) {
        return recordCourseMapper.getRepairLessonTeamDetail(yearPart, quarterNum, subjectsId, startDate, endDate, lessonType, teacherId, gradeId, studentName, yearClassId, classify, trackType, teamId);
    }

    /**
     * 课时核对列表（上课记录）
     */
    public IPage<StudentClassLogRep> studentClassLog(IPage<StudentClassLogRep> page, Wrapper wrapper, String yearPart, String quarter, String startDate, String endDate, String status, String schoolId, String yearClassId, String subjectsId, String studentName, String courseType, String checkType, String gradeId, String staffId, String isOther) {

        IPage<StudentClassLogRep> studentClassLogRepIPage = recordCourseMapper.studentClassLog(page, wrapper, yearPart, quarter, startDate, endDate, status, schoolId, yearClassId, subjectsId, studentName, courseType, checkType, gradeId, staffId, isOther);
        for (StudentClassLogRep studentClassLogRep : studentClassLogRepIPage.getRecords()) {
            /*if (!studentClassLogRep.getCheckType().equals(1) || studentClassLogRep.getResidueCourseCount() == null){
                RecordCourseCheck recordCourseCheck = iRecordCourseCheckService.getResidueCount(studentClassLogRep.getYearPart(),studentClassLogRep.getQuarterNum(),studentClassLogRep.getStudentId(),studentClassLogRep.getSubjectsId());
                if (recordCourseCheck!=null){
                    studentClassLogRep.setResidueCourseCount(recordCourseCheck.getResidueCourseCount());
                    studentClassLogRep.setResiduePrice(recordCourseCheck.getResiduePrice());
                }
            }
            if (studentClassLogRep.getStatus().equals(StatusRecordEnum.LEAVE) && studentClassLogRep.getIsRepair().equals(1) && !studentClassLogRep.getCheckType().equals(1)){
                RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(studentClassLogRep.getId());
                if (recordCourseLack != null){
                    studentClassLogRep.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
                }
            }*/
            RecordCourseCheck getResidueCount = iRecordCourseCheckService.getResidueCount(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getStudentId(), studentClassLogRep.getSubjectsId());
            studentClassLogRep.setResidueCourseCount(getResidueCount.getResidueCourseCount());
            Long useCourseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getSubjectsId(), studentClassLogRep.getStudentId(), 1);
            studentClassLogRep.setUseCourseCount(useCourseCount);
            Integer recordCourseCount = this.getLeaveCount(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getLessonType(), studentClassLogRep.getStudentId(), studentClassLogRep.getSubjectsId());
            studentClassLogRep.setLeaveCount(recordCourseCount);
        }

        return studentClassLogRepIPage;
    }

    public IPage<StudentClassLogRep> studentClassLogParticulars(IPage<StudentClassLogRep> page, Wrapper wrapper) {
        IPage<StudentClassLogRep> studentClassLogRepIPage = recordCourseMapper.studentClassLogParticulars(page, wrapper);
        for (StudentClassLogRep studentClassLogRep : studentClassLogRepIPage.getRecords()) {
            RecordCourseCheck getResidueCount = iRecordCourseCheckService.getResidueCount(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getStudentId(), studentClassLogRep.getSubjectsId());
            studentClassLogRep.setResidueCourseCount(getResidueCount.getResidueCourseCount());
            Long useCourseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getSubjectsId(), studentClassLogRep.getStudentId(), 1);
            studentClassLogRep.setUseCourseCount(useCourseCount);
            Integer recordCourseCount = this.getLeaveCount(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getLessonType(), studentClassLogRep.getStudentId(), studentClassLogRep.getSubjectsId());
            studentClassLogRep.setLeaveCount(recordCourseCount);
        }

        return studentClassLogRepIPage;
    }

    @Override
    public IPage<StudentClassLogRep> studentClassLogParticulars2(IPage<StudentClassLogRep> iPage, String yearPart, String quarterNum, String startDate, String endDate, String schoolId, String subjectsId, String checkType, String teacherId, String lessonType, String isRestrict, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
        IPage<StudentClassLogRep> studentClassLogRepIPage = recordCourseMapper.studentClassLogParticulars2(iPage, yearPart, quarterNum, startDate, endDate, schoolId, subjectsId, checkType, teacherId, lessonType, isRestrict, authAdminContent, leadDataRs);
        if (isRestrict.equals("0")) {
            for (StudentClassLogRep studentClassLogRep : studentClassLogRepIPage.getRecords()) {
                RecordCourseCheck getResidueCount = iRecordCourseCheckService.getResidueCount(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getStudentId(), studentClassLogRep.getSubjectsId());
                studentClassLogRep.setResidueCourseCount(getResidueCount.getResidueCourseCount());
                Long useCourseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getSubjectsId(), studentClassLogRep.getStudentId(), 1);
                studentClassLogRep.setUseCourseCount(useCourseCount);
                Integer recordCourseCount = this.getLeaveCount(studentClassLogRep.getYearPart(), studentClassLogRep.getQuarterNum(), studentClassLogRep.getLessonType(), studentClassLogRep.getStudentId(), studentClassLogRep.getSubjectsId());
                studentClassLogRep.setLeaveCount(recordCourseCount);
            }
        }
        return studentClassLogRepIPage;
    }

    @Override
    public BigDecimal studentClassTeacherGetMoney(Wrapper wrapper) {
        return recordCourseMapper.studentClassTeacherGetMoney(wrapper);
    }

    @Override
    public List<StudentClassLogRep> studentClassLogRate(String schoolId, String startDate, String endDate, String subjectsId, String yearPart, String quarterNum, String type, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {
//        return recordCourseMapper.studentClassLogRate(schoolId, startDate, endDate, subjectsId, yearPart, quarterNum, type);
        return recordCourseMapper.studentClassLogRate2(schoolId, startDate, endDate, subjectsId, yearPart, quarterNum, type, authAdminContent, leadDataRs);
    }

    /**
     * 扣课时
     *
     * @param recordCourseId
     * @return
     */
    @Override
    public Result buckleCourseForHandle(Long recordCourseId) {
        RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseId);
        Result rs;
        if (recordCourse == null) {
            rs = new Result(Code.ERROR, "", "上课记录不存在");
            return rs;
        }
        if (recordCourse.getIsDeductHouse() == 1) {
            rs = new Result(Code.ERROR, "", "已扣课时，不要重复扣课时");
            return rs;
        }
        Long userCourse = iStudentGradeService.getStudentUseCourseCountAllSchool(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), recordCourse.getLessonType());
        if (userCourse >= 45) {
            RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
            if (recordCourseLeave != null) {
                Result bRs = this.greaterBuckleMoney(recordCourse.getId(), recordCourseLeave.getId());
                if (!bRs.getCode().equals(Code.OK)) {
                    rs = new Result(Code.ERROR, "", "扣课时失败");
                } else {
                    rs = bRs;
                }
            } else {
                RecordCourseCheck getResidueCount = iRecordCourseCheckService.getResidueCount(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
                Integer residueCount = getResidueCount.getResidueCourseCount();
                if (residueCount.equals(0)) {
                    //throw new CommonException(ResultCode.RESIDUE_COUNT_ZERO);
                    rs = new Result(Code.ERROR, "", "扣课时失败，剩余课时为0");
                } else {
                    rs = iAdminFeignClient.recordActionConsume(recordCourse);
                }
            }
        } else {
            rs = new Result(Code.ERROR, "", "还未上满15次课，不能扣课时");
        }
        return rs;
    }

    /**
     * 上满15次课的，手动消课
     *
     * @param recordCourseParam
     * @return
     */
    @Transactional
    public boolean recordActionConsume(RecordCourse recordCourseParam) {

        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseParam.getId());
            Long studentId = recordCourse.getStudentId();
            String studentName = recordCourse.getStudentName();
            Integer courseType = recordCourse.getCourseType();
            Long schedulingDetailId = recordCourse.getSchedulingDetailId();

            Long useCouseCount = iStudentGradeService.getStudentUseCourseCountAllSchool(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), recordCourse.getLessonType());
            if (useCouseCount < 45) {
                throw new CommonException(ResultCode.NOT_FIFTEEN_USE_COUNSE);
            }

            //不等于0
            if (recordCourse.getIsDeductHouse().equals(1)) {
                return true;
            }

            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                return false;
            }
            /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            if(grade==null){
                return false;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return false;
            }*/
            Long courseId = null;
            String courseName = "";
            if (courseSchedulingDetailInfo.getGradeId() != null) {
                Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }

            //扣多少个课时(备注唯一这里与自动扣课时不一样)
            Integer buckleClassHouse = 3;
            Integer teaGainHour = 3;

            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());

            //使用本学期使用课时
            //Long useCount = iStudentGradeService.getStudentUseCourseCount(courseSchedulingDetailInfo.getYearPart(),courseSchedulingDetailInfo.getQuarter(),courseSchedulingDetailInfo.getSchoolId(),courseSchedulingDetailInfo.getSubjectsId(),studentId,courseSchedulingDetailInfo.getLessonType());

            //状态不为消课的
            /*if (!courseType.equals(5)){
                //请假，请假的不添加数据，直接返回
                if (useCount >=45){
                    //大于45课时，请假的不添加记录
                    return true;
                }
            }*/

            //Student student = studentMapper.selectById(studentId);

            Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType());

            if (residueCourseCount < buckleClassHouse) {
                RecordError recordError = new RecordError();
                recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                recordError.setStudentId(studentId);
                recordError.setContent("此学生：" + recordCourse.getStudentName() + ",课程：" + courseSchedulingDetailInfo.getCourseName() + "剩余课时不足：" + buckleClassHouse);
                iRecordErrorService.save(recordError);
                //此学生该课程没有可用课时
                return false;
            }

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            //请假未补数量
            Integer lackCount = 0;
            try {
                lackCount = recordCourseMapper.getLackCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), recordCourse.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getLessonType());
            } catch (Exception e) {
            }
            if (residueCourseCount == buckleClassHouse && lackCount.equals(0)) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType());

            Integer diffClassHosue = buckleClassHouse;//还差多少课时

            Integer teaGainHourAll = 0;//老师得课时总课时
            BigDecimal teaGainMoneyAll = new BigDecimal(0);

            BigDecimal buckleClassMoneyAll = new BigDecimal(0);
            BigDecimal buckleClassHourAll = new BigDecimal(0);

            //老师课时获得金额
            BigDecimal courseInMoney = staff.getCourseInMoney();
            BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
            if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                return false;
            }

            iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));//先删除详情
            Long lastOrderDetailId = null;
            for (OrderDetail orderDetail : orderDetailList) {
                if (diffClassHosue == 0) {
                    continue;
                }

                CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                if (coursePricing == null) {
                    //此学生数据异常
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                    iRecordErrorService.save(recordError);
                    continue;
                }

                Integer userClassHouse = 0;//本次使用课时
                //本次要扣的课时大于等于剩余课时
                if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                    userClassHouse = orderDetail.getResidueCourseCount();
                    diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                } else {
                    userClassHouse = diffClassHosue;
                    diffClassHosue = 0;
                }

                RecordCost recordCost = new RecordCost();
                recordCost.setId(idWorker.nextId());
                recordCost.setRecordCourseId(recordCourse.getId());
                recordCost.setOrderDetailId(orderDetail.getId());
                lastOrderDetailId = orderDetail.getId();

                /**
                 * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                 */
                BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                //本次扣多少个课时
                BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                //学生此次扣课时使用金额
                BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                /**
                 * compareTo 反回1 表示大于，0等于，-1小于
                 * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                 */

                //缺课未补的金额
                BigDecimal lackMoney = iRecordCourseLackService.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                BigDecimal residuePrice = orderDetail.getResiduePrice().subtract(lackMoney);//剩余金额
                if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                    residuePrice = new BigDecimal(0);
                if (userClassHouse == orderDetail.getResidueCourseCount()) {
                    //使用可是等于剩余课时
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                    //本次使用金额大于剩余金额
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                }

                buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);

                //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                recordCost.setBuckleClassHouse(userClassHouse);

                Integer teacherGetClassHosue = (userClassHouse / 3) * teaGainHour;//教师得多少课时

                //BigDecimal teaGainMoney = new BigDecimal(teacherGetClassHosue).divide(courseInCount, BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);
                BigDecimal teaGainMoney = new BigDecimal(0);
                //镇级
                if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                    teaGainMoney = new BigDecimal(17);
                } else {
                    teaGainMoney = new BigDecimal(20);
                }
                teaGainHourAll = teaGainHourAll + teacherGetClassHosue;
                teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额
                }
                //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                /**
                 使用课时：use_course_count
                 上课累计使用金额：use_price
                 剩余课时：residue_course_count
                 剩余金额：residue_price
                 */
                //扣课时
                //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                orderDetail.setUseCourseCount(useCourseCountForOrder);//累计使用课时

                Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                //到课
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                }
                iOrderDetailService.updateById(orderDetail);

                //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                //recordCostUpdateWrapper.eq("id",recordCost.getId());
                iRecordCostService.save(recordCost);

                //更新分班里使用的课时
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.eq("lesson_type", courseSchedulingDetailInfo.getLessonType());
                studentGradeQueryWrapper.eq("reading_status", 1);
                //studentGradeQueryWrapper.eq("grade_id",courseSchedulingDetailInfo.getGradeId());
                studentGradeQueryWrapper.last("limit 1");
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(courseSchedulingDetailInfo.getSchoolId(), orderDetail.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), true, courseSchedulingDetailInfo.getLessonType());
                }

                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//累计使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    studentGrade.setReadingStatus(readingStatusEnum);
                    iStudentGradeService.updateById(studentGrade);
                    recordCourse.setStudentGradeId(studentGrade.getId());
                }
                if (readingStatusEnum.getKey().equals(5)) {
                    studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
                    studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
                    studentGradeQueryWrapper.ne("status", 2);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.orderByDesc("created_at");
                    List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGradeUpdate : studentGradeList) {
                        studentGradeUpdate.setReadingStatus(readingStatusEnum);
                        iStudentGradeService.updateById(studentGradeUpdate);
                    }

                }
            }
            recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
            recordCourse.setOrderDetailId(lastOrderDetailId);
            recordCourse.setIsDeductHouse(1);
            recordCourse.setRemark("满15次后，消课扣课时");
            //到课
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                recordCourse.setIsDeductMoney(1);
            } else {
                recordCourse.setIsDeductMoney(0);
            }

            recordCourse.setDeductType(3);//扣课时方式，0未知，1自动，2是手动3满15次后按消课扣课时

            //UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
            //recordCourseUpdateWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //recordCourseUpdateWrapper.eq("student_id",recordCourse.getStudentId());
            this.updateById(recordCourse);

            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                //缺课的金额暂时保存
                RecordCourseLack recordCourseLack = new RecordCourseLack();
                recordCourseLack.setId(recordCourse.getId());
                recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
                recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                recordCourseLack.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourseLack.setTeacherGetHouse(teaGainHourAll);
                recordCourseLack.setTeacherGetMoney(teaGainMoneyAll);
                iRecordCourseLackService.saveOrUpdate(recordCourseLack);
            }

            //到课，发送微信提醒
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("course_status", 1);//课时是否异常，异常的不推送家长,正常：1
            Long courseStatusCount = iStudentGradeService.count(studentGradeQueryWrapper);
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                if (courseStatusCount > 0) {
                    StringBuilder first = new StringBuilder();
                    first.append(courseSchedulingDetailInfo.getGradeName()).append("(").append(courseSchedulingDetailInfo.getSchoolName()).append(")").append("新增上课记录，请查看");
                    String keyword1 = studentName;
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(courseSchedulingDetailInfo.getSchoolDate()).append(" ").append(courseSchedulingDetailInfo.getTimeStart()).append("-").append(courseSchedulingDetailInfo.getTimeEnd());
                    StringBuilder keyword3 = new StringBuilder();
                    keyword3.append("考勤状态为“上课" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");

                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;//剩余课时
                    StringBuilder keyword4 = new StringBuilder();
                    keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    //StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    //List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    try {
                        //iWecharsBindService.useCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), "", courseSchedulingDetailInfo.getId() + "" + studentId);
                    } catch (Exception e) {

                    }
                }
            }
            return true;
        } catch (Exception e) {
            //System.out.println("recordActionError:"+e.getMessage());
            return false;
        }
    }

    /**
     * 大于15次课的，扣除补课金额
     *
     * @param recordCourseId
     * @param byRecordId
     * @return
     */
    @Override
    @Transactional
    public Result greaterBuckleMoney(Long recordCourseId, Long byRecordId) {

        //获取出记上课信息
        RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseId);
        if (recordCourse == null)
            return new Result(Code.ERROR, "", "");
        //已扣过课时
        if (recordCourse.getIsDeductHouse().equals(1))
            return new Result(Code.ERROR, "", "");

        //缺课记上课记录
        RecordCourse recordCourseOld = recordCourseMapper.selectById(byRecordId);
        if (recordCourseOld == null)
            return new Result(Code.ERROR, "", "");

        //已扣过的，不再扣
        if (recordCourseOld.getIsDeductMoney().equals(1)) {
            return new Result(Code.ERROR, "", "");
        }

        RecordCourseLack recordCourseLack = recordCourseLackMapper.selectById(recordCourseOld.getId());
        if (recordCourseLack == null)
            return new Result(Code.ERROR, "", "");

        OrderDetail orderDetail = iOrderDetailService.getById(recordCourseLack.getOrderDetailId());
        if (orderDetail == null)
            return new Result(Code.ERROR, "", "");

        BigDecimal buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        if (orderDetail.getResiduePrice().compareTo(recordCourseLack.getBuckleClassMoney()) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));//剩余金额
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
        iOrderDetailService.updateById(orderDetail);

        //更新记录
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCourse.setStudentGradeId(recordCourseOld.getStudentGradeId());
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(buckleClassMoney));
        recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney().add(recordCourseLack.getTeacherGetMoney()));
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCourse.setByRecordId(recordCourseOld.getId());//被补课id
        recordCourseMapper.updateById(recordCourse);

        //更新原来的数据
        recordCourseOld.setBuckleClassHouse(0);
        recordCourseOld.setBuckleClassMoney(new BigDecimal(0));
        recordCourseOld.setTeacherGetHouse(0);
        recordCourseOld.setTeacherGetMoney(new BigDecimal(0));
        recordCourseOld.setIsRepair(1);
        recordCourseOld.setIsDeductHouse(1);
        recordCourseOld.setIsDeductMoney(1);
        recordCourseOld.setStatus(StatusRecordEnum.LEAVE);//请假
        recordCourseMapper.updateById(recordCourseOld);

        /*UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
        recordCostUpdateWrapper.set("buckle_class_house",0);
        recordCostUpdateWrapper.eq("record_course_id",recordCourseOld.getId());
        iRecordCostService.update(null,recordCostUpdateWrapper);*/
        //删除原来的数据
        iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourseOld.getId()));

        //添加记录详情
        RecordCost recordCostNew = new RecordCost();
        //BeanUtils.copyProperties(recordCostOld,recordCostNew);
        recordCostNew.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCostNew.setBuckleClassMoney(buckleClassMoney);
        recordCostNew.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCostNew.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCostNew.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCostNew.setId(idWorker.nextId());
        recordCostNew.setRecordCourseId(recordCourse.getId());
        iRecordCostService.save(recordCostNew);

        recordCourseLack.setIsDeductMoney(1);
        recordCourseLackMapper.updateById(recordCourseLack);
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("buckleHouse", recordCourse.getBuckleClassHouse());
        objectMap.put("buckleMoney", recordCourse.getBuckleClassMoney());
        return new Result(Code.OK, objectMap, "扣课时成功");
    }

    @Override
    public RecordCourse getLeaveData(Integer yearPart,
                                     Integer quarterNum,
                                     Integer lessonType,
                                     Long studentId,
                                     Long subjectsId) {
        return recordCourseMapper.getLeaveData(yearPart, quarterNum, lessonType, studentId, subjectsId);
    }

    @Override
    public Integer getLeaveCount(Integer yearPart,
                                 Integer quarterNum,
                                 Integer lessonType,
                                 Long studentId,
                                 Long subjectsId) {
        return recordCourseMapper.getLeaveCount(yearPart, quarterNum, lessonType, studentId, subjectsId);
    }

    @Override
    public StudentClassLogRep uncheckedCount(Wrapper wrapper, String yearPart, String quarter, String staffId) {
        return recordCourseMapper.uncheckedCount(wrapper, yearPart, quarter, staffId);
    }

    /**
     * 刷题到勤
     */
    @Override
    public List<RecordCourse> getBrushQuestionsDiligently(String schoolId,
                                                          String subjectsId,
                                                          String yearPart,
                                                          String quarterNum,
                                                          String StartDate,
                                                          String EndDate,
                                                          String gradeId,
                                                          String teacherId,
                                                          String status,
                                                          String timeStart,
                                                          String timeEnd,
                                                          Integer lessonType,
                                                          String yearClassIdStr,
                                                          String startLessonNum,
                                                          String endLessonNum,
                                                          String isRebrush,
                                                          Integer isCount,
                                                          String studentName,
                                                          String schoolType,
                                                          String teacherName,
                                                          Integer type
    ) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        LocalDate localDateNow = LocalDate.now();

        LocalDate startDate = LocalDate.parse(StartDate);
        LocalDate endDate = LocalDate.parse(EndDate);

        String mixDate = this.mixDateFinal;//添加一个系统上线前的日期
        String startDateLast = mixDate;
        String endDateLast = mixDate;

        boolean isHistory = true;//是否历史数据（当天的除外是历史数据）
        if (yearPart.equals(quarterNow.getYearPart().toString()) && quarterNum.equals(quarterNow.getNum().toString()) && StartDate.equals(localDateNow.toString()) && EndDate.equals(localDateNow.toString())) {
            isHistory = false;
        }
        if (StringUtils.isBlank(yearClassIdStr)) {
            yearClassIdStr = "0,1,2,3,4,5,6,7,8,9";
        }
        List<RecordCourse> recordCourseList = null;

        if (StringUtils.isNotBlank(startLessonNum) && StringUtils.isNotBlank(endLessonNum)) {
            //按课次查看
//            startDateLast = "";
//            endDateLast = localDateNow.minusDays(1).toString();
            StartDate = localDateNow.toString();
            EndDate = localDateNow.toString();
        } else {
            if (startDate.isBefore(localDateNow) && endDate.isBefore(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = EndDate;
//                StartDate = mixDate;
//                EndDate = mixDate;
            } else if (startDate.isBefore(localDateNow) && endDate.equals(localDateNow)) {
//                startDateLast = StartDate;
//                endDateLast = localDateNow.minusDays(1).toString();
//                StartDate = localDateNow.toString();
            }
        }

        /**
         * 是否赠送时间内
         */
        Integer giveCount = recordCourseMapper.getSignGiveCount(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), localDateNow.toString());
        String readingStatus = "1";
        if (giveCount > 0) {
            readingStatus = "1,5";
        }

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(Integer.parseInt(yearPart), Integer.parseInt(quarterNum));
        StringBuilder courseSchedulingDetailName = new StringBuilder();
        courseSchedulingDetailName.append("course_scheduling_detail");
        if (quarter.getId() != quarterNow.getId()) {
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(yearPart);
            courseSchedulingDetailName.append("_");
            courseSchedulingDetailName.append(quarterNum);
        }

        // 获取校区id
//        schoolId = iSchoolQuarterService.getChilIds(Integer.parseInt(yearPart), Integer.parseInt(quarterNum), schoolId);

        if (lessonType.equals(1)) {
            //精品课

        } else {
            if (isRebrush.equals("1")) {
                Long storSubjectsId = null;
                if (StringUtils.isNotBlank(subjectsId)) {
                    storSubjectsId = Long.parseLong(subjectsId);
                }
                recordCourseMapper.storeAgainBrushData(Integer.valueOf(yearPart), Integer.valueOf(quarterNum), storSubjectsId, yearClassIdStr, null);
            }

            LocalDate planEndDate = LocalDate.now();
            // 判断结束日期是否大于当前日期，如果大于当前日期，那么planEndDate等于结束日期
            if (endDate.isAfter(planEndDate)) {
                planEndDate = endDate;
            }

            recordCourseList = recordCourseMapper.getBrushQuestionsDiligently(schoolId, subjectsId, yearPart, quarterNum, startDateLast, endDateLast, StartDate, EndDate, gradeId, teacherId, status, timeStart, timeEnd, lessonType, yearClassIdStr, startLessonNum, endLessonNum, isRebrush, readingStatus, String.valueOf(courseSchedulingDetailName), isCount, studentName, schoolType, String.valueOf(planEndDate), teacherName, type);
        }
        return recordCourseList;
    }

    @Override
    public Integer getRecordCountArrive(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId) {
        return recordCourseMapper.getRecordCountArrive(yearPart, quarterNum, studentId, subjectsId);
    }

    /**
     * 获取最近三个学期最后一次上课记录
     *
     * @param lessonType
     * @param studentId
     * @return
     */
    @Override
    public RecordCourse getRecordCourseByLastThreeQuarter(Integer yearPart, Integer quarterNum, Integer lessonType, Long studentId, String subjectsId) {

        Quarter quarter = iQuarterService.getQuarterForYearAndNum(yearPart, quarterNum);
        RecordCourse recordCourse = null;
        try {
            if (ObjectUtil.isNotNull(quarter)) {
                Long startQuarterId = quarter.getId();
                Long endQuarterId = quarter.getId();

                if (quarter.getId() > 2) {
                    startQuarterId = startQuarterId - 2;
                }
                recordCourse = recordCourseMapper.getRecordCourseByLastThreeQuarter(lessonType, studentId, subjectsId, startQuarterId, endQuarterId);
                if (ObjectUtil.isNotNull(recordCourse) && recordCourse.getOldTeacherId() == null) {
                    QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("student_id", studentId);
                    studentGradeQueryWrapper.eq("year_part", recordCourse.getYearPart());
                    studentGradeQueryWrapper.eq("quarter_num", recordCourse.getQuarter());
                    studentGradeQueryWrapper.eq("is_last", 1);
                    studentGradeQueryWrapper.eq("lesson_type", 1);
                    studentGradeQueryWrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    studentGradeQueryWrapper.last("limit 1");
                    StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                    if (ObjectUtil.isNotNull(studentGrade)) {
                        Grade grade = iGradeService.getById(studentGrade.getGradeId());
                        if (ObjectUtil.isNotNull(grade)) {
                            recordCourse.setOldGradeId(grade.getTeacherId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            SystemErrorLog systemErrorLog = new SystemErrorLog();
            systemErrorLog.setContent(e.getMessage());
            systemErrorLog.setType(2);
            systemErrorLog.setRemark("获取最近三个学期最后一次上课记录");
            iSystemErrorLogService.save(systemErrorLog);
        }

        return recordCourse;
    }

    /**
     * 请假未补的数量,不包含请假已扣金额的数据
     *
     * @param yearPart
     * @param quarterNum
     * @param studentId
     * @param subjectsId
     * @param lessonType
     * @return
     */
    @Override
    public Integer getLackCount(Integer yearPart, Integer quarterNum, Long schoolId, Long studentId, Long subjectsId, Integer lessonType) {
        return recordCourseMapper.getLackCount(yearPart, quarterNum, schoolId, studentId, subjectsId, lessonType);
    }

    @Override
    public Integer getMaxTaskLesson(Integer YearPart, Integer QuarterNum, String SubjectsId, Long courseVersionId, Integer categoryId) {
        Integer tastMaxLessonNum = 20;
        try {
            if (SubjectsId.equals("2")) {
                tastMaxLessonNum = iMathematicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(), QuarterNum.toString(), SubjectsId, courseVersionId, categoryId);
            } else if (SubjectsId.equals("3")) {
                tastMaxLessonNum = iPhysicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(), QuarterNum.toString(), SubjectsId, courseVersionId, categoryId);
            }
        } catch (Exception e) {
        }
        return tastMaxLessonNum;
    }
}
